package middleware

import (
	"go-chat/common"
	"go-chat/utils"
	"strings"

	"github.com/gin-gonic/gin"
)

func JWTAuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		//从请求头中获取token
		authHeader := c.GetHeader("Authorization")
		if authHeader == "" {
			common.Fail(c, 401, "token无效或不存在!")
			c.Abort()
			return
		}
		//处理"Bearer xxxx"格式
		parts := strings.SplitN(authHeader, " ", 2)
		if len(parts) != 2 && parts[0] != "Bearer" {
			common.Fail(c, 401, "token格式错误!")
			c.Abort()
			return
		}
		//解析token
		claims, err := utils.ParseToken(parts[1])
		if err != nil {
			common.Fail(c, 401, "token无效或不存在!")
			c.Abort()
			return
		}

		//注入id到上下文
		c.Set("id", claims.ID)
		c.Next()
	}
}
